<template>
  <div>
    <!-- 面包屑导航 -->
    <el-header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>
    <!-- 主体部分 -->
    <el-card>
      <!-- 警告条 -->
      <el-alert
              title="注意：只允许为第三级分类设置相关参数！"
              type="warning" show-icon>
      </el-alert>

      <!-- 选择商品分类 -->
      <p>
        <span class="title">选择商品分类：</span>
        <el-cascader
                v-model="selectId"
                @change="getParamsData"
                :options="categoriesData"
                :props="categoriesProps"
                :show-all-levels="false">
        </el-cascader>
      </p>

      <!-- 标签页选择部件 -->
      <el-tabs v-model="activeName" @tab-click="getParamsData">
        <!-- 动态参数选项卡 -->
        <el-tab-pane label="动态参数" name="dynamic">
          <!-- 添加参数按钮 -->
          <el-button type="primary" size="mini" :disabled="!selectId"
                     @click="addParamDialogVisible = true">添加参数
          </el-button>
          <!-- 参数表格 -->
          <el-table :data="tableData.dynamic" stripe border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 使用tag标签加载values内容 -->
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.values"
                        type="primary" closable
                        @close="delValue(index, scope.row)">{{ item }}
                </el-tag>
                <!-- 添加值输入框 -->
                <!-- keyup和blur不能写同一个函数 否则会调用两次 -->
                <el-input class="input-new-tag" size="small"
                          v-if="scope.row.inputVisible"
                          ref="saveTagInput"
                          v-model="scope.row.inputValue"
                          @keyup.enter.native="$refs.saveTagInput.blur()"
                          @blur="addValue(scope.row)">
                </el-input>
                <!-- 添加值按钮 -->
                <el-button v-else size="small"
                           @click="inputBtnClick(scope.row)">
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <!-- 参数名 -->
            <el-table-column prop="name" label="参数名称"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini">修改</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性选项卡 -->
        <el-tab-pane label="静态属性" name="static">
          <el-button type="primary" size="mini" :disabled="!selectId"
                     @click="addParamDialogVisible = true">添加属性
          </el-button>
          <!-- 属性表格 -->
          <el-table :data="tableData.static" stripe border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.values"
                        type="primary" closable
                        @close="delValue(index, scope.row)">{{ item }}
                </el-tag>
                <!-- 添加值输入框 -->
                <!-- keyup和blur不能写同一个函数 否则会调用两次 -->
                <el-input class="input-new-tag" size="small"
                          v-if="scope.row.inputVisible"
                          ref="saveTagInput"
                          v-model="scope.row.inputValue"
                          @keyup.enter.native="$refs.saveTagInput.blur()"
                          @blur="addValue(scope.row)">
                </el-input>
                <!-- 添加值按钮 -->
                <el-button v-else size="small"
                           @click="inputBtnClick(scope.row)">
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <!-- 属性名 -->
            <el-table-column prop="name" label="属性名称"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini">修改</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加按钮弹出框 -->
      <el-dialog :title="'添加' + dialogTitle" width="30%"
                 :visible.sync="addParamDialogVisible"
                 @close="addParamClose" @open="addForm.cid=selectId">
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item :label="dialogTitle" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="addParamDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParamSubmit">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类原始数据
      sourceData: [],
      // 标签页选中 默认选中动态参数
      activeName: 'dynamic',
      // dynamic是动态参数表格数据，static是静态属性表格数据
      tableData: {
        dynamic: [],
        static: []
      },
      // 商品分类选择框参数
      categoriesProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        // hover时展开子菜单
        expandTrigger: 'hover',
        // 获取的是该节点的值还是节点路径值的数组
        emitPath: false
      },
      // 添加分类表单
      addForm: { name: '', cid: 0, type: '' },
      // 添加分类表单校验规则
      addFormRules: {
        name: [
          { required: true, message: '该项为必填项', trigger: 'blur' },
          { max: 15, message: '长度必须小于15个字符', trigger: 'blur' }
        ]
      },
      // 商品分类选择框选择的值
      selectId: 0,
      // 添加弹出框是否显示
      addParamDialogVisible: false
    }
  },
  computed: {
    // 商品分类数据
    categoriesData() {
      // 列表复制
      let newData = JSON.parse(JSON.stringify(this.sourceData))
      for (let item of newData)
        for (let item1 of item.children)
          for (let item2 of item1.children)
            item2.children = undefined
      return newData
    },
    dialogTitle() {
      if (this.activeName === 'dynamic')
        return '动态参数'
      return '静态属性'
    }
  },
  methods: {
    // 获取商品分类数据
    async getCategoriesData() {
      let { data: res } = await this.$ajax.get('categories/')
      if (res.status === 'success') {
        this.sourceData = res.data
        this.$message.success('获取商品分类参数成功')
      } else
        this.$message.error('获取商品分类参数失败')
    },
    // 将values中的内容用<@>切割
    // 为每一个数据添加inputVisible和inputValue
    myOptions(data) {
      // 将数据中的values用<@>切割
      // 如果非空则使用<@>切割
      // 为空则直接赋值空数组

      // 为item添加inputVisible属性
      // 控制新增值输入框的显示和隐藏
      for (let item of data) {
        item.values = item.values ? item.values.split('<@>') : []
        item.inputVisible = false
        item.inputValue = ''
      }
    },
    // 通过type和id获取参数数据
    async getParamsData() {
      this.tableData.dynamic = []
      this.tableData.static = []
      let { data: res } = await this.$ajax.get(`params/${this.activeName}/${this.selectId}/`)
      if (res.status === 'success') {
        // 将values中的内容用<@>切割
        this.myOptions(res.data)
        this.tableData[this.activeName] = res.data
      }
    },
    // 添加弹出框点击提交时调用
    async addParamSubmit() {
      this.addForm.type = this.activeName
      let { data: res } = await this.$ajax.post('params/add/',
              this.$ajax.stringify(this.addForm))
      if (res.status === 'success') {
        this.myOptions(res.data)
        this.tableData[this.activeName] = res.data
        this.$message.success('添加参数成功')
        this.addParamDialogVisible = false
      } else
        this.$message.error('添加参数失败')
    },
    // 添加弹出框关闭时调用
    addParamClose() {
      this.$refs.addForm.resetFields()
      this.addForm.cid = 0
      this.addForm.type = ''
    },
    // 将值添加到数据并发送给后端
    async addValue(row) {
      row.inputVisible = false
      // 去除两端空格
      row.inputValue = row.inputValue.trim()
      // 值为空则不操作
      if (!row.inputValue) return
      // 将数据发送给后端
      let values = [...row.values, row.inputValue].join('<@>')
      let { data: res } = await this.$ajax.post('params/set_values/',
              this.$ajax.stringify({ id: row.id, values }))
      if (res.status === 'OK') {
        row.values.push(row.inputValue)
        row.inputValue = ''
        this.$message.success('添加成功')
      } else
        this.$message.error('添加失败')
    },
    // 删除参数值时调用
    async delValue(index, row) {
      // 拷贝数组
      let values = [...row.values]
      values.splice(index, 1)
      values = values.join('<@>')
      // 发起网络请求
      let { data: res } = await this.$ajax.post('params/set_values/',
              this.$ajax.stringify({ id: row.id, values }))
      if (res.status === 'OK') {
        // 删除本地数据内容
        row.values.splice(index, 1)
        this.$message.success('删除参数成功')
      } else
        this.$message.error('删除参数失败')

    },
    // 添加值tag按钮被点击
    inputBtnClick(row) {
      // 显示输入框
      row.inputVisible = true
      // 等待页面渲染完成再调用focus函数获取焦点
      this.$nextTick(_ => {
        // 使输入文本框获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  created() {
    this.getCategoriesData()
  }
}
</script>

<style scoped>
.el-header {
  display: flex;
  align-items: center;
}

.el-alert /deep/ .el-alert__content {
  display: flex;
  align-items: center;
}

.title {
  font-size: 14px;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 10px 10px;
}

.input-new-tag {
  width: 150px;
}
</style>